package com.ld.xuanKe.controller;

import com.alibaba.excel.EasyExcel;
import com.ld.xuanKe.entity.Course;
import com.ld.xuanKe.listener.MyUploadCourseDataListener;
import com.ld.xuanKe.service.CourseService;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @ProjectName xuanKe
 * @ClassName CourseAction
 * @Author 刘邓
 * @Date 2023-12-09 11:01
 */
@Controller
@Scope("prototype")
public class CourseAction implements ModelDriven<Course> {
	@Resource
	private CourseService courseService;
	private Course course;
	private String startTime0;
	private String endTime0;
	//excel模板下载
	private InputStream inputStream;
	private String filename;
	//导入excel
	private File uploadFile;
	private String uploadFileFileName;

	public Course getModel() {
		course = new Course();
		return course;
	}

	public String add() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		if (course.getCapacity() < 60) {
			session.setAttribute("message", "课程容量不得低于60");
			return "course-add";
		}
		if (course.getStartTime() != null && course.getEndTime() != null) {
			if (course.getStartTime().compareTo(course.getEndTime()) >= 0) {
				session.setAttribute("message", "添加失败,时间顺序有误");
				return "course-add";
			}
		}
		course.setSelected(0);
		int add = courseService.add(course);
		if (add == 1) {
			session.setAttribute("message", "添加成功");
		} else {
			session.setAttribute("message", "添加失败");
		}
		return "course-add";
	}

	public String update() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		if (course.getCapacity() < 60) {
			session.setAttribute("message", "课程容量不得低于60");
			return "course-update";
		}
		if (course.getCapacity() < course.getSelected()) {
			session.setAttribute("message", "已选人数不能大于课程容量");
			return "course-update";
		}
		if (course.getStartTime() != null && course.getEndTime() != null) {
			if (course.getStartTime().compareTo(course.getEndTime()) >= 0) {
				session.setAttribute("message", "更新失败,时间顺序有误");
				return "course-update";
			}
		}
		int update = courseService.update(course);
		if (update == 1) {
			session.setAttribute("message", "更新成功");
		} else {
			session.setAttribute("message", "更新失败");
		}
		return "course-update";
	}

	public String delete() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();

		int delete = courseService.delete(course.getId());
		if (delete == 1) {
			session.setAttribute("message", "删除成功");
		} else {
			session.setAttribute("message", "删除失败");
		}
		return "course-delete";
	}

	public String updateTime() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		int updateTime = courseService.updateTime(course.getStartTime(), course.getEndTime());
		if (updateTime == 1) {
			session.setAttribute("message", "设置成功");
		} else {
			session.setAttribute("message", "删除失败");
		}
		return "course-updateTime";
	}

	public String getStartTime0() {
		return startTime0;
	}

	public void setStartTime0(String startTime0) {
		this.startTime0 = startTime0;
		if (!StringUtils.isEmpty(startTime0)) {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
			LocalDateTime dateTime = LocalDateTime.parse(startTime0, formatter);
			Timestamp timestamp = Timestamp.valueOf(dateTime);
			course.setStartTime(timestamp);
		}
	}

	public String getEndTime0() {
		return endTime0;
	}

	public void setEndTime0(String endTime0) {
		this.endTime0 = endTime0;
		if (!StringUtils.isEmpty(endTime0)) {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
			LocalDateTime dateTime = LocalDateTime.parse(endTime0, formatter);
			Timestamp timestamp = Timestamp.valueOf(dateTime);
			course.setEndTime(timestamp);
		}
	}

	//导出excel
	public void downLoadCourses() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpSession session = request.getSession();
			HttpServletResponse resp = ServletActionContext.getResponse();
			List<Course> courses = courseService.list();
			System.out.println(courses);
			resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			resp.setCharacterEncoding("utf-8");
			// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
			String fileName = URLEncoder.encode("课程信息", "UTF-8").replaceAll("\\+", "%20");
			resp.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			EasyExcel.write(resp.getOutputStream(), Course.class).sheet("课程信息").doWrite(courses);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	//	模板下载
	public String excelTemplate() {
		return "success";
	}

	public InputStream getInputStream() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpSession session = request.getSession();
			String filePath = "/home/upload/template.xlsx";
			inputStream = new FileInputStream(ServletActionContext.getRequest().getServletContext().getRealPath(filePath));
			return inputStream;
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}


	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	//导入excel
	public String importExcel() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpSession session = request.getSession();
			if (uploadFile == null) {
				session.setAttribute("message", "导入失败");
				return "course-import";
			}
			EasyExcel.read(new FileInputStream(uploadFile), Course.class, new MyUploadCourseDataListener()).sheet().doRead();
			session.setAttribute("message", "导入成功");
			return "course-import";
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}

	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}

	//	删除无效课程
	public String deleteNotValid() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		int i = courseService.deleteNotValid();
		if (i == 1) {
			session.setAttribute("message", "删除成功");
		} else {
			session.setAttribute("message", "删除失败");
		}
		return "course-deleteNotValid";
	}
}
